Skip to content

第一章 预备知识

一、Python基础

1. 列表推导式与条件赋值

在生成一个数字序列的时候,在Python中可以如下写出:

python
L = []
def my_func(x):
    return 2*x
for i in range(5):
    L.append(my_func(i))
L
[0, 2, 4, 6, 8]

事实上可以利用列表推导式进行写法上的简化:[* for i in *]。其中,第一个*为映射函数,其输入为后面i指代的内容,第二个*表示迭代的对象。

python
[my_func(i) for i in range(5)]
[0, 2, 4, 6, 8]

列表表达式还支持多层嵌套,如下面的例子中第一个for为外层循环,第二个为内层循环:

python
[m+'_'+n for m in ['a', 'b'] for n in ['c', 'd']]
['a_c', 'a_d', 'b_c', 'b_d']

除了列表推导式,另一个实用的语法糖是带有if选择的条件赋值,其形式为value = a if condition else b

python
value = 'cat' if 2>1 else 'dog'
value
'cat'

等价于如下的写法:

python
a, b = 'cat', 'dog'
condition = 2 > 1 # 此时为True
if condition:
    value = a
else:
    value = b

下面举一个例子,截断列表中超过5的元素,即超过5的用5代替,小于5的保留原来的值:

python
L = [1, 2, 3, 4, 5, 6, 7]
[i if i <= 5 else 5 for i in L]
[1, 2, 3, 4, 5, 5, 5]

2. 匿名函数与map方法

有一些函数的定义具有清晰简单的映射关系,例如上面的my_func函数,这时候可以用匿名函数的方法简洁地表示:

python
my_func = lambda x: 2*x
my_func(3)
6
python
multi_para_func = lambda a, b: a + b
multi_para_func(1, 2)
3

但上面的用法其实违背了“匿名”的含义,事实上它往往在无需多处调用的场合进行使用,例如上面列表推导式中的例子,用户不关心函数的名字,只关心这种映射的关系:

python
[(lambda x: 2*x)(i) for i in range(5)]
[0, 2, 4, 6, 8]

对于上述的这种列表推导式的匿名函数映射,Python中提供了map函数来完成,它返回的是一个map对象,需要通过list转为列表:

python
list(map(lambda x: 2*x, range(5)))
[0, 2, 4, 6, 8]

对于多个输入值的函数映射,可以通过追加迭代对象实现:

python
list(map(lambda x, y: str(x)+'_'+y, range(5), list('abcde')))
['0_a', '1_b', '2_c', '3_d', '4_e']

3. zip对象与enumerate方法

zip函数能够把多个可迭代对象打包成一个元组构成的可迭代对象,它返回了一个zip对象,通过tuple, list可以得到相应的打包结果:

python
L1, L2, L3 = list('abc'), list('def'), list('hij')
list(zip(L1, L2, L3))
[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
python
tuple(zip(L1, L2, L3))
(('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j'))

往往会在循环迭代的时候使用到zip函数:

python
for i, j, k in zip(L1, L2, L3):
     print(i, j, k)
a d h
b e i
c f j

enumerate是一种特殊的打包,它可以在迭代时绑定迭代元素的遍历序号:

python
L = list('abcd')
for index, value in enumerate(L):
     print(index, value)
0 a
1 b
2 c
3 d

zip对象也能够简单地实现这个功能:

python
for index, value in zip(range(len(L)), L):
     print(index, value)
0 a
1 b
2 c
3 d

当需要对两个列表建立字典映射时,可以利用zip对象:

python
dict(zip(L1, L2))
{'a': 'd', 'b': 'e', 'c': 'f'}

既然有了压缩函数,那么Python也提供了*操作符和zip联合使用来进行解压操作:

python
zipped = list(zip(L1, L2, L3))
zipped
[('a', 'd', 'h'), ('b', 'e', 'i'), ('c', 'f', 'j')]
python
list(zip(*zipped)) # 三个元组分别对应原来的列表
[('a', 'b', 'c'), ('d', 'e', 'f'), ('h', 'i', 'j')]

二、Numpy基础

1. np数组的构造

最一般的方法是通过array来构造:

python
import numpy as np
np.array([1,2,3])
array([1, 2, 3])

下面讨论一些特殊数组的生成方式:

【a】等差序列:np.linspace, np.arange

python
np.linspace(1,5,11) # 起始、终止(包含)、样本个数
array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ])
python
np.arange(1,5,2) # 起始、终止(不包含)、步长
array([1, 3])

【b】特殊矩阵:zeros, eye, full

python
np.zeros((2,3)) # 传入元组表示各维度大小
array([[0., 0., 0.],
       [0., 0., 0.]])
python
np.eye(3) # 3*3的单位矩阵
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
python
np.eye(3, k=1) # 偏移主对角线1个单位的伪单位矩阵
array([[0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 0.]])
python
np.full((2,3), 10) # 元组传入大小,10表示填充数值
array([[10, 10, 10],
       [10, 10, 10]])
python
np.full((2,3), [1,2,3]) # 每行填入相同的列表
array([[1, 2, 3],
       [1, 2, 3]])

【c】随机矩阵:np.random

最常用的随机生成函数为rand, randn, randint, choice,它们分别表示0-1均匀分布的随机数组、标准正态的随机数组、随机整数组和随机列表抽样:

python
np.random.rand(3) # 生成服从0-1均匀分布的三个随机数
array([0.92340835, 0.20019461, 0.40755472])
python
np.random.rand(3, 3) # 注意这里传入的不是元组,每个维度大小分开输入
array([[0.8012362 , 0.53154881, 0.05858554],
       [0.13103034, 0.18108091, 0.30253153],
       [0.00528884, 0.99402007, 0.36348797]])

对于服从区间ab上的均匀分布可以如下生成:

python
a, b = 5, 15
(b - a) * np.random.rand(3) + a
array([6.59370831, 8.03865138, 9.19172546])

一般的,可以选择已有的库函数:

python
np.random.uniform(5, 15, 3)
array([11.26499636, 13.12311185,  6.00774156])

randn生成了N(0,I)的标准正态分布:

python
np.random.randn(3)
array([ 1.87000209,  1.19885561, -0.58802943])
python
np.random.randn(2, 2)
array([[-1.3642839 , -0.31497567],
       [-1.9452492 , -3.17272882]])

对于服从方差为σ2均值为μ的一元正态分布可以如下生成:

python
sigma, mu = 2.5, 3
mu + np.random.randn(3) * sigma
array([1.56024917, 0.22829486, 7.3764211 ])

同样的,也可选择从已有函数生成:

python
np.random.normal(3, 2.5, 3)
array([3.53517851, 5.3441269 , 3.51192744])

randint可以指定生成随机整数的最小值最大值(不包含)和维度大小:

python
low, high, size = 5, 15, (2,2) # 生成5到14的随机整数
np.random.randint(low, high, size)
array([[ 5, 12],
       [14,  9]])

choice可以从给定的列表中,以一定概率和方式抽取结果,当不指定概率时为均匀采样,默认抽取方式为有放回抽样:

python
my_list = ['a', 'b', 'c', 'd']
np.random.choice(my_list, 2, replace=False, p=[0.1, 0.7, 0.1 ,0.1])
array(['b', 'a'], dtype='<U1')
python
np.random.choice(my_list, (3,3))
array([['c', 'b', 'd'],
       ['d', 'a', 'd'],
       ['a', 'c', 'd']], dtype='<U1')

当返回的元素个数与原列表相同时,不放回抽样等价于使用permutation函数,即打散原列表:

python
np.random.permutation(my_list)
array(['c', 'a', 'd', 'b'], dtype='<U1')

最后,需要提到的是随机种子,它能够固定随机数的输出结果:

python
np.random.seed(0)
np.random.rand()
0.5488135039273248
python
np.random.seed(0)
np.random.rand()
0.5488135039273248

2. np数组的变形与合并

【a】转置:T

python
np.zeros((2,3)).T
array([[0., 0.],
       [0., 0.],
       [0., 0.]])

【b】合并操作:r_, c_

对于二维数组而言,r_c_分别表示上下合并和左右合并:

python
np.r_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
python
np.c_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])

一维数组和二维数组进行合并时,应当把其视作列向量,在长度匹配的情况下只能够使用左右合并的c_操作:

python
try:
     np.r_[np.array([0,0]),np.zeros((2,1))]
except Exception as e:
     Err_Msg = e
Err_Msg
ValueError('all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)')
python
np.r_[np.array([0,0]),np.zeros(2)]
array([0., 0., 0., 0.])
python
np.c_[np.array([0,0]),np.zeros((2,3))]
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.]])

【c】维度变换:reshape

reshape能够帮助用户把原数组按照新的维度重新排列。在使用时有两种模式,分别为C模式和F模式,分别以逐行和逐列的顺序进行填充读取。

python
target = np.arange(8).reshape(2,4)
target
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
python
target.reshape((4,2), order='C') # 按照行读取和填充
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
python
target.reshape((4,2), order='F') # 按照列读取和填充
array([[0, 2],
       [4, 6],
       [1, 3],
       [5, 7]])

特别地,由于被调用数组的大小是确定的,reshape允许有一个维度存在空缺,此时只需填充-1即可:

python
target.reshape((4,-1))
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])

下面将n*1大小的数组转为1维数组的操作是经常使用的:

python
target = np.ones((3,1))
target
array([[1.],
       [1.],
       [1.]])
python
target.reshape(-1)
array([1., 1., 1.])

3. np数组的切片与索引

数组的切片模式支持使用slice类型的start:end:step切片,还可以直接传入列表指定某个维度的索引进行切片:

python
target = np.arange(9).reshape(3,3)
target
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
python
target[:-1, [0,2]]
array([[0, 2],
       [3, 5]])

此外,还可以利用np.ix_在对应的维度上使用布尔索引,但此时不能使用slice切片:

python
target[np.ix_([True, False, True], [True, False, True])]
array([[0, 2],
       [6, 8]])
python
target[np.ix_([1,2], [True, False, True])]
array([[3, 5],
       [6, 8]])

当数组维度为1维时,可以直接进行布尔索引,而无需np.ix_

python
new = target.reshape(-1)
new[new%2==0]
array([0, 2, 4, 6, 8])

4. 常用函数

为了简单起见,这里假设下述函数输入的数组都是一维的。

【a】where

where是一种条件函数,可以指定满足条件与不满足条件位置对应的填充值:

python
a = np.array([-1,1,-1,0])
np.where(a>0, a, 5) # 对应位置为True时填充a对应元素,否则填充5
array([5, 1, 5, 5])

【b】nonzero, argmax, argmin

这三个函数返回的都是索引,nonzero返回非零数的索引,argmax, argmin分别返回最大和最小数的索引:

python
a = np.array([-2,-5,0,1,3,-1])
np.nonzero(a)
(array([0, 1, 3, 4, 5], dtype=int64),)
python
a.argmax()
4
python
a.argmin()
1

【c】any, all

any指当序列至少 存在一个 True或非零元素时返回True,否则返回False

all指当序列元素 全为 True或非零元素时返回True,否则返回False

python
a = np.array([0,1])
a.any()
True
python
 a.all()
False

【d】cumprod, cumsum, diff

cumprod, cumsum分别表示累乘和累加函数,返回同长度的数组,diff表示和前一个元素做差,由于第一个元素为缺失值,因此在默认参数情况下,返回长度是原数组减1

python
a = np.array([1,2,3])
a.cumprod()
array([1, 2, 6], dtype=int32)
python
a.cumsum()
array([1, 3, 6], dtype=int32)
python
np.diff(a)
array([1, 1])

【e】 统计函数

常用的统计函数包括max, min, mean, median, std, var, sum, quantile,其中分位数计算是全局方法,因此不能通过array.quantile的方法调用:

python
target = np.arange(5)
target
array([0, 1, 2, 3, 4])
python
target.max()
4
python
np.quantile(target, 0.5) # 0.5分位数
2.0

但是对于含有缺失值的数组,它们返回的结果也是缺失值,如果需要略过缺失值,必须使用nan*类型的函数,上述的几个统计函数都有对应的nan*函数。

python
target = np.array([1, 2, np.nan])
target
array([ 1.,  2., nan])
python
target.max()
nan
python
np.nanmax(target)
2.0
python
np.nanquantile(target, 0.5)
1.5

对于协方差和相关系数分别可以利用cov, corrcoef如下计算:

python
target1 = np.array([1,3,5,9])
target2 = np.array([1,5,3,-9])
np.cov(target1, target2)
array([[ 11.66666667, -16.66666667],
       [-16.66666667,  38.66666667]])
python
np.corrcoef(target1, target2)
array([[ 1.        , -0.78470603],
       [-0.78470603,  1.        ]])

最后,需要说明二维Numpy数组中统计函数的axis参数,它能够进行某一个维度下的统计特征计算,当axis=0时结果为列的统计指标,当axis=1时结果为行的统计指标:

python
target = np.arange(1,10).reshape(3,-1)
target
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
python
target.sum(0)
array([12, 15, 18])
python
target.sum(1)
array([ 6, 15, 24])

5. 广播机制

广播机制用于处理两个不同维度数组之间的操作,这里只讨论不超过两维的数组广播机制。

【a】标量和数组的操作

当一个标量和数组进行运算时,标量会自动把大小扩充为数组大小,之后进行逐元素操作:

python
res = 3 * np.ones((2,2)) + 1
res
array([[4., 4.],
       [4., 4.]])
python
res = 1 / res
res
array([[0.25, 0.25],
       [0.25, 0.25]])

【b】二维数组之间的操作

当两个数组维度完全一致时,使用对应元素的操作,否则会报错,除非其中的某个数组的维度是m×1或者1×n,那么会扩充其具有1的维度为另一个数组对应维度的大小。例如,1×2数组和3×2数组做逐元素运算时会把第一个数组扩充为3×2,扩充时的对应数值进行赋值。但是,需要注意的是,如果第一个数组的维度是1×3,那么由于在第二维上的大小不匹配且不为1,此时报错。

python
res = np.ones((3,2))
res
array([[1., 1.],
       [1., 1.],
       [1., 1.]])
python
res * np.array([[2,3]]) # 第二个数组扩充第一维度为3
array([[2., 3.],
       [2., 3.],
       [2., 3.]])
python
res * np.array([[2],[3],[4]]) # 第二个数组扩充第二维度为2
array([[2., 2.],
       [3., 3.],
       [4., 4.]])
python
res * np.array([[2]]) # 等价于两次扩充,第二个数组两个维度分别扩充为3和2
array([[2., 2.],
       [2., 2.],
       [2., 2.]])

【c】一维数组与二维数组的操作

当一维数组Ak与二维数组Bm,n操作时,等价于把一维数组视作A1,k的二维数组,使用的广播法则与【b】中一致,当k!=nk,n都不是1时报错。

python
np.ones(3) + np.ones((2,3))
array([[2., 2., 2.],
       [2., 2., 2.]])
python
np.ones(3) + np.ones((2,1))
array([[2., 2., 2.],
       [2., 2., 2.]])
python
np.ones(1) + np.ones((2,3))
array([[2., 2., 2.],
       [2., 2., 2.]])

6. 向量与矩阵的计算

【a】向量内积:dot

ab=iaibi
python
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
22

【b】向量范数和矩阵范数:np.linalg.norm

在矩阵范数的计算中,最重要的是ord参数,可选值如下:

ordnorm for matricesnorm for vectors
NoneFrobenius norm2-norm
'fro'Frobenius norm/
'nuc'nuclear norm/
infmax(sum(abs(x), axis=1))max(abs(x))
-infmin(sum(abs(x), axis=1))min(abs(x))
0/sum(x != 0)
1max(sum(abs(x), axis=0))as below
-1min(sum(abs(x), axis=0))as below
22-norm (largest sing. value)as below
-2smallest singular valueas below
other/sum(abs(x)**ord)**(1./ord)
python
matrix_target =  np.arange(4).reshape(-1,2)
matrix_target
array([[0, 1],
       [2, 3]])
python
np.linalg.norm(matrix_target, 'fro')
3.7416573867739413
python
np.linalg.norm(matrix_target, np.inf)
5.0
python
np.linalg.norm(matrix_target, 2)
3.702459173643833
python
vector_target =  np.arange(4)
vector_target
array([0, 1, 2, 3])
python
np.linalg.norm(vector_target, np.inf)
3.0
python
np.linalg.norm(vector_target, 2)
3.7416573867739413
python
np.linalg.norm(vector_target, 3)
3.3019272488946263

【c】矩阵乘法:@

[Am×pBp×n]ij=k=1pAikBkj
python
a = np.arange(4).reshape(-1,2)
a
array([[0, 1],
       [2, 3]])
python
b = np.arange(-4,0).reshape(-1,2)
b
array([[-4, -3],
       [-2, -1]])
python
a@b
array([[ -2,  -1],
       [-14,  -9]])

三、练习

Ex1:利用列表推导式写矩阵乘法

一般的矩阵乘法根据公式,可以由三重循环写出,请将其改写为列表推导式的形式。

python
M1 = np.random.rand(2,3)
M2 = np.random.rand(3,4)
res = np.empty((M1.shape[0],M2.shape[1]))
for i in range(M1.shape[0]):
    for j in range(M2.shape[1]):
        item = 0
        for k in range(M1.shape[1]):
            item += M1[i][k] * M2[k][j]
        res[i][j] = item
(np.abs((M1@M2 - res) < 1e-15)).all() # 排除数值误差
True

Ex2:更新矩阵

设矩阵 Am×n ,现在对 A 中的每一个元素进行更新生成矩阵 B ,更新方法是 Bij=Aijk=1n1Aik ,例如下面的矩阵为 A ,则 B2,2=5×(14+15+16)=3712 ,请利用 Numpy 高效实现。

A=[123456789]

Ex3:卡方统计量

设矩阵Am×n,记Bij=(i=1mAij)×(j=1nAij)i=1mj=1nAij,定义卡方值如下:

χ2=i=1mj=1n(AijBij)2Bij

请利用Numpy对给定的矩阵A计算χ2

python
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))

Ex4:改进矩阵计算的性能

Zm×n的矩阵,BU分别是m×pp×n的矩阵,BiB的第i行,UjU的第j列,下面定义R=i=1mj=1nBiUj22Zij,其中a22表示向量a的分量平方和iai2

现有某人根据如下给定的样例数据计算R的值,请充分利用Numpy中的函数,基于此问题改进这段代码的性能。

python
np.random.seed(0)
m, n, p = 100, 80, 50
B = np.random.randint(0, 2, (m, p))
U = np.random.randint(0, 2, (p, n))
Z = np.random.randint(0, 2, (m, n))
def solution(B=B, U=U, Z=Z):
    L_res = []
    for i in range(m):
        for j in range(n):
            norm_value = ((B[i]-U[:,j])**2).sum()
            L_res.append(norm_value*Z[i][j])
    return sum(L_res)
solution(B, U, Z)
100566

Ex5:连续整数的最大长度

输入一个整数的Numpy数组,返回其中严格递增连续整数子数组的最大长度,正向是指递增方向。例如,输入[1,2,5,6,7],[5,6,7]为具有最大长度的连续整数子数组,因此输出3;输入[3,2,1,2,3,4,6],[1,2,3,4]为具有最大长度的连续整数子数组,因此输出4。请充分利用Numpy的内置函数完成。(提示:考虑使用nonzero, diff函数)